﻿using System.Windows;
namespace Company.Logic
{
    public class SequenceManager : ISequenceManager
    {
        public ManualResetEvent ManualReset { get; private set; }
        public CancellationTokenSource CancellationTokenSource { get; private set; } = new CancellationTokenSource();

        private Action<SequenceManager> _SequenceCallback; // 委托回调

        private Task _SequenceTask;
        public bool IsRunning { get;private set; } = false; // 是否运行
        public bool IsStop { get; private set; } = false; // 是否停止/结束
        public bool IsPause { get; private set; } = false; // 是否暂停
        public SequenceManager()
        {
            
        }
        public SequenceManager(Action<SequenceManager> sequenceCallback)
        {
            ManualReset = new ManualResetEvent(false);
            _SequenceCallback = sequenceCallback;
        }
        /// <summary>
        /// 开始
        /// </summary>
        public void Start()
        {
            // 确保之前的任务已完成
            if (_SequenceTask != null && !_SequenceTask.IsCompleted)
            {
                // 等待任务完成
                return;
            }
            if (CancellationTokenSource.Token.IsCancellationRequested)
                CancellationTokenSource = new CancellationTokenSource();
            ManualReset.Set();
            _SequenceTask = Task.Run(OnSequenceCallback, CancellationTokenSource.Token);
            IsRunning = true;
            IsStop = false;
            IsPause = false;
        }
        /// <summary>
        /// 停止/结束
        /// </summary>
        public void Stop()
        {
            CancellationTokenSource?.Cancel();
            // 如果结束任务，不阻塞继续运行。
            ManualReset.Set();
            IsRunning = false;
            IsStop = true;
            IsPause = false;
        }
        /// <summary>
        /// 暂停
        /// </summary>
        public void Pause()
        {
            ManualReset?.Reset();
            IsStop = false;
            IsPause = true;
        }
        /// <summary>
        /// 继续/恢复
        /// </summary>
        public void Resume()
        {
            ManualReset?.Set();
            IsStop = false;
            IsPause = false;
        }
        /// <summary>
        /// 中断标志/等待继续
        /// </summary>
        public void WaitOne()
        {
            // 先阻塞
            ManualReset?.WaitOne();
            // 后异常捕获
            CancellationTokenSource.Token.ThrowIfCancellationRequested();
            IsStop = false;
            IsPause = true;
        }
        /// <summary>
        /// 回调
        /// </summary>
        private void OnSequenceCallback()
        {
            try
            {
                while (!CancellationTokenSource.IsCancellationRequested)
                {
                    _SequenceCallback?.Invoke(this);
                }
            }
            catch (OperationCanceledException ex)
            {
                MessageBox.Show($"{ex.Message}");
            }
        }
    }
}
